package org.dtrd.modules.quartz.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.flup.entity.po.DtrdEntRdFlupAppointmentRecord;
import org.dtrd.modules.flup.service.IDtrdEntRdFlupAppointmentRecordService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author qr
 * @date 2021/12/30 12:56
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
@Slf4j
public class CheckFlupStatusJob implements Job {

    @Autowired
    private IDtrdEntRdFlupAppointmentRecordService appointmentRecordService;


    /**
     * 如果 now > 预约的结束时间,  已预约/待复诊 -> 未复诊
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        DateTime now = DateTime.now();
        LambdaQueryWrapper<DtrdEntRdFlupAppointmentRecord> queryWrapper = Wrappers.lambdaQuery(DtrdEntRdFlupAppointmentRecord.class)
                .in(DtrdEntRdFlupAppointmentRecord::getFlupStatus,
                    Constant.FlupStatus.HasAppointment.getStatus(),
                    Constant.FlupStatus.WaitToVisit.getStatus()
                );
        List<DtrdEntRdFlupAppointmentRecord> records = appointmentRecordService.list(queryWrapper);
        for (DtrdEntRdFlupAppointmentRecord record : records) {
            Date date = wrapperDate(record.getFlupDate(), record.getFlupTime());
            Constant.FlupStatus flupStatus = Constant.FlupStatus.valueOf(record.getFlupStatus());
            switch (flupStatus){
                // 已预约/待复诊 -> 未复诊
                case HasAppointment:
                case WaitToVisit:
                    if (now.isAfter(date)) {
                        Constant.FlupStatus newStatus = Constant.FlupStatus.NotVisited;
                        record.setFlupStatus(newStatus.getStatus());
                        log.info("CheckFlupStatusJob.execute: 更新患者复诊状态，patientId:{}, {}->{}",
                                record.getPatientId(), flupStatus.getName(), newStatus.getName());
                    }
                    break;
            }
        }
        // 更新设置的状态
        appointmentRecordService.updateBatchById(records);
    }

    /**
     * 将 flupDate 和 flupTime 组合成一个 date 对象
     */
    private Date wrapperDate(Date flupDate, Integer flupTime){
        if (flupTime == null) {
            throw new IllegalArgumentException("CheckFlupStatusJob.wrapperDate 的 flupTime 不能为空");
        }
        String flupDateStr = DateUtil.format(flupDate, DateUtils.date_sdf.get().toPattern());
        String endTime = Constant.FlupTime.valueOf(flupTime).getEndTime();
        String newDate = flupDateStr + " " + endTime + ":00";
        return DateUtil.parse(newDate, DateUtils.datetimeFormat.get().toPattern());
    }
}
